﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PortalCurriculo.Util.CustomControls
{
    public sealed class PopupMenu : WebControl
    {
        protected override void OnLoad(EventArgs e)
        {
            Width = new Unit(100, UnitType.Percentage);

            if (SaveButton != null)
            {
                SaveButton.ID = "Save";
                SaveButton.Order = 0;
                SaveButton.Type = ButtonType.Link;
                SaveButton.TextButton = SaveButton.TextButton ?? new PopupButton.TextInfo();
                SaveButton.TextButton.Text = SaveText;
                SaveButton.CausesValidation = true;
            }

            CancelButton = CancelButton ?? new PopupButton();

            CancelButton.ID = "Cancel";
            CancelButton.Order = 1;
            CancelButton.Type = ButtonType.Link;
            CancelButton.TextButton = new PopupButton.TextInfo { Text = CancelText, Click = Cancel_Click };
            CancelButton.CausesValidation = false;

            var popupButtons = new List<PopupButton> { CancelButton };

            if (SaveButton != null) popupButtons.Add(SaveButton);
            if (Button1 != null) popupButtons.Add(Button1);
            if (Button2 != null) popupButtons.Add(Button2);

            foreach (PopupButton popupButton in popupButtons.OrderBy(button => button.Order))
            {
                Controls.Add(popupButton.BuildControl(ValidationGroup));
            }

            base.OnLoad(e);
        }

        public PopupButton SaveButton { get; set; }
        public PopupButton Button1 { get; set; }
        public PopupButton Button2 { get; set; }
        public PopupButton CancelButton { get; set; }
        public string ValidationGroup { get; set; }

        public string SaveText { get; set; }
        public string CancelText { get; set; }

        private void Cancel_Click(object sender, EventArgs e)
        {
            GetPopup(Parent);
        }

        private void GetPopup(Control parent)
        {
            foreach (object control in parent.Controls)
            {
                if (!control.GetType().Equals(typeof(Popup))) continue;

                ((Popup)control).Close();
                return;
            }

            GetPopup(parent.Parent);
        }
    }
}